package com.hui.controller.login;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hui.constant.ShopConstants;
import com.hui.entity.dao.ShopUser;
import com.hui.entity.enums.ShopCommonEnum;
import com.hui.entity.enums.auth.SmsTypeEnum;
import com.hui.model.auth.RegParam;
import com.hui.model.auth.VerityParam;
import com.hui.service.UserService;
import com.hui.util.RedisUtils;
import com.hui.util.ResponseResult;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 用户注册控制器
 */
@RestController
@RequiredArgsConstructor
@CrossOrigin
@RequestMapping("/api")
@Slf4j
public class AuthController {

    private final UserService userService;
    private final RedisUtils redisUtil;

    /**
     * 注册接口
     *
     * @param
     * @return
     */
    @PostMapping("/register")
    @ApiOperation(value = "H5/APP注册新用户", notes = "H5/APP注册新用户")
    public ResponseResult getOneUser(@Valid @RequestBody RegParam param) {
        Object codeObj = redisUtil.get("code_" + param.getAccount());
        if (codeObj == null) {
            return ResponseResult.fail("请先获取验证码");
        }
        String code = codeObj.toString();
        if (!StrUtil.equals(code, param.getCaptcha())) {
            return ResponseResult.fail("验证码错误");
        }
        ShopUser shopUser = userService.getOne(Wrappers.<ShopUser>lambdaQuery()
                .eq(ShopUser::getPhone, param.getAccount()).or()
                .eq(ShopUser::getUsername, param.getAccount()), false);
        if (ObjectUtil.isNotNull(shopUser)) {
            return ResponseResult.fail("用户已存在");
        }
        return userService.register(param);
    }


    @PostMapping("/register/verify")
    @ApiOperation(value = "短信验证码发送", notes = "短信验证码发送")
    public ResponseResult verify(@Validated @RequestBody VerityParam param) {
        ShopUser shopUser = userService.getOne(Wrappers.<ShopUser>lambdaQuery()
                .eq(ShopUser::getPhone, param.getPhone()), false);
        //注册验证
        if (SmsTypeEnum.REGISTER.getValue().equals(param.getType()) && ObjectUtil.isNotNull(shopUser)) {
            return ResponseResult.fail("手机号已注册");
        }
        //登录验证
        if (SmsTypeEnum.LOGIN.getValue().equals(param.getType()) && ObjectUtil.isNull(shopUser)) {
            return ResponseResult.fail("账号不存在");
        }
        String codeKey = "code_" + param.getPhone();
        if (ObjectUtil.isNotNull(redisUtil.get(codeKey))) {
            return ResponseResult.fail("10分钟内有效:" + redisUtil.get(codeKey).toString());
        }
        String code = RandomUtil.randomNumbers(ShopConstants.YSHOP_SMS_SIZE);

        //redis存储
        redisUtil.set(codeKey, code, ShopConstants.YSHOP_SMS_REDIS_TIME);

        String enable = redisUtil.getY("sms_enable");
        if (ShopCommonEnum.ENABLE_2.getValue().toString().equals(enable)) {
            return ResponseResult.okResult(code);
        }

        return ResponseResult.okResult(code);
//        return ResponseResult.okResult("发送成功，请注意查收");

    }

    @ApiOperation(value = "退出登录", notes = "退出登录")
    @PostMapping(value = "/auth/logout")
    public ResponseResult<String> logout(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        log.info("token为： {}", bearerToken);
        //TODO 计划删除 redis 用户信息
        return ResponseResult.okResult("退出成功");
    }


}
